
var list0 = require('../../data/cet4.js')
var list1 = require('../../data/cet6.js')
var list2 = require('../../data/primary.js')
var list3 = require('../../data/high.js')
var list4 = require('../../data/kaoyan.js')
var list5 = require('../../data/kaoyan_import.js')
//var qcloud = require('../../vendor/wafer2-client-sdk/index')
//var config = require('../../config')
const db = wx.cloud.database();
var util = require('../../utils/util.js')
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    da1: "",
    da2: "",
    da3: "",
    da4: "",
    daan: false,
    showDaan: false,
    complete: false,
    true_num: 0,//本次正确数
    max_num:0,//历史最高
    rank:[],//排行榜信息
    myimg:'',//我的头像
    start:false,//开始答题页面显示
    list: list0,//词库选择
    listnum:2800,//随机数范围
    show: false,//控制下拉列表的显示隐藏，false隐藏、true显示
    selectData: ['四级', '六级', '初级词汇', '高中词汇', '考研', '专八'],//下拉列表的数据
    index: 0,//选择的下拉列表下标
    animationType: "animated bounce infinite", //初始的正确数字动画效果
    bounceInDown: "animated bounceInDown ",//回答错误的动画
    color4: 'black',
    color3: 'black',
    color2: 'black',
    color1: 'black',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var max_num=wx.getStorageSync("max_num")
    this.setData({
      max_num:max_num
    })
    let that =this
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: res => {
            //  console.log(res)
              that.setData({
                myimg: res.userInfo.avatarUrl,
              })
            }
         }
      )}
    }
})
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.getmessage()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      start:false,
      complete: false,
      showDaan:false,
      show:false
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      start:false,
      complete: false,
      showDaan: false
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    return {
      title: "我在菜鸟单词测试，答对了" + this.data.true_num + "道题，你也快来测一测吧！",
    }

  },
  //开始答题
  start(){
    this.search()
   this.setData({
     start:true,
     animationType: "animated bounce infinite",
   })
  },

  //选择definition
  choice(e) {
    console.log(e)
    var checked = e.currentTarget.dataset['index']
    if (e.currentTarget.id === this.data.true_definition) {
      var true_btn = this.data.true_btn
      switch (true_btn) {
        case 'color1': this.setData({ color1: "green" }); break;
        case 'color2': this.setData({ color2: "green" }); break;
        case 'color3': this.setData({ color3: "green" }); break;
        case 'color4': this.setData({ color4: "green" }); break;
      }
      this.setData({ daan: true, true_num: this.data.true_num + 1 })
    this.next();
    } else {
      switch (checked) {
        case '1': this.setData({ color1: "red" }); break;
        case '2': this.setData({ color2: "red" }); break;
        case '3': this.setData({ color3: "red" }); break;
        case '4': this.setData({ color4: "red" }); break;
      }
      switch (true_btn) {
        case 'color1': this.setData({ color1: "green" }); break;
        case 'color2': this.setData({ color2: "green" }); break;
        case 'color3': this.setData({ color3: "green" }); break;
        case 'color4': this.setData({ color4: "green" }); break;
      }
      var true_num=this.data.true_num
      var max_num=this.data.max_num
      this.setData({ daan: false })
      const innerAudioContext = wx.createInnerAudioContext()
      innerAudioContext.autoplay = true
      innerAudioContext.src = 'https://media-audio1.baydn.com/us%2Fs%2Fsa%2Fsad_v4.mp3'
      innerAudioContext.onPlay(() => {
      })
      if(true_num>max_num){//结束之后判断正确数量
        wx.setStorageSync("max_num",true_num)
        this.setData({ max_num:true_num })
        this.getData()
      }
      setTimeout(()=>{
        this.setData({
          showDaan: true, animationType: "animated hinge"
        })
      },1000) 
     // this.getRankGlobalData();

    }
  },
  search() {
    var listnum = this.data.listnum
    console.log(listnum)
    var idx = Math.floor(Math.random() * listnum) + 1
    var list=this.data.list
    var word = list.wordList[idx]
    console.log(word)
    var that = this
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/?word=' + word,
      data: {},
      method: 'GET',
      success: function (res) {
        setTimeout(()=>{
        const innerAudioContext = wx.createInnerAudioContext()
        innerAudioContext.autoplay = true
        innerAudioContext.src=res.data.data.audio
        innerAudioContext.play()
        innerAudioContext.onPlay(() => {
        })
        that.setData({
            color4: 'black',
            color3: 'black',
            color2: 'black',
            color1: 'black',
          title: res.data.data.content,
          true_definition: res.data.data.definition
        })
      }, 400)
        var num = Math.floor(Math.random() * 400) + 1
        if (num < 100) {
          var da2 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search2(da2)
          var da3 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search3(da3)
          var da4 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search4(da4)
          setTimeout(()=>{
          that.setData({
            da1: res.data.data.definition,
            da2: that.data.da22,
            da3: that.data.da33,
            da4: that.data.da44,
            true_btn: "color1"
            })
          }, 400)
        }
        if (100 < num && num < 200) {
          var da1 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search1(da1)
          var da3 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search3(da3)
          var da4 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search4(da4)
          setTimeout(() => {
          that.setData({
            da2: res.data.data.definition,
            da1: that.data.da11,
            da3: that.data.da33,
            da4: that.data.da44,
            true_btn: "color2"
            })
          }, 400)
        }
        if (num < 300 && num > 200) {
          var da2 = list.wordList[Math.floor(Math.random() * listnum) + 1]
           that.search2(da2)
          var da1 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search1(da1)
          var da4 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search4(da4)
          setTimeout(() => {
          that.setData({
            da3: res.data.data.definition,
            da2: that.data.da22,
            da1: that.data.da11,
            da4: that.data.da44,
            true_btn: "color3"
          })
        }, 400)
        }
        if (num > 300) {
          var da2 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          var da22 = that.search2(da2)
          var da3 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search3(da3)
          var da1 = list.wordList[Math.floor(Math.random() * listnum) + 1]
          that.search1(da1)
          setTimeout(() => {
          that.setData({
            da4: res.data.data.definition,
            da2: that.data.da22,
            da1: that.data.da11,
            da3: that.data.da33,
            true_btn: "color4"
            })
          }, 400)
        }
      }
    })
  },
  search1(word) {
    var that = this
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/?word=' + word,
      data: {},
      method: 'GET',
      success: function (res) {
        that.setData({
          da11: res.data.data.definition
        })
      }
    })
  },
  search2(word) {
    var that = this
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/?word=' + word,
      data: {},
      method: 'GET',
      success: function (res) {
        that.setData({
          da22: res.data.data.definition
        })
      }
    })
  },
  search3(word) {
    var that = this
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/?word=' + word,
      data: {},
      method: 'GET',
      success: function (res) {
        that.setData({
          da33: res.data.data.definition
        })
      }
    })
  },
  search4(word) {
    var that = this
    wx.request({
      url: 'https://api.shanbay.com/bdc/search/?word=' + word,
      data: {},
      method: 'GET',
      success: function (res) {
        that.setData({
          da44: res.data.data.definition
        })
      }
    })
  },
  next() {
    this.search()
  },
  end(){
  this.setData({
  start:false,
  showDaan: false,
  complete: false,
  num: 1,
  true_num: 0,
    color4: 'black',
    color3: 'black',
    color2: 'black',
    color1: 'black',
})
  },
  complete() {
    this.paihang()
    this.setData({
      complete: true,
    })
  },
  last(){
    this.setData({
      complete: false,
    })
  },
  again() {
    this.setData({
      showDaan: false,
      complete: false,
      num: 1,
      true_num: 0,
      color4: 'black',
      color3: 'black',
      color2: 'black',
      color1: 'black',
      animationType: "animated bounce infinite" //初始的动画效果
    })
    this.search()
  },


   // 将缓存中的用户数据记录到数据库
   getData: function () {
      db.collection('userData').doc(this.data.countID).update({
        data: {
          max_num: wx.getStorageSync("max_num"),
        },
        success: res => {
          console.log('更新数据成功', res)
        },
        fail: err => {
          icon: 'none',
          console.error('[数据库] [更新记录] 失败：', err)
        }
      })

  },

  getmessage: function () {
    // 获取此次用户的openid
    var _openid = wx.getStorageSync("_openid");
    console.log("成了", _openid);
    const db = wx.cloud.database();
    // 获取数据库中用户的信息
    const cont = db.collection('usermessage');
    cont.where({
      _openid: _openid,
    }).get({
      success: res => {
        var username = res.data[0].username;
        this.setData({
          username: username,
        })
        console.log("用户数据:", this.data.username);
      }
    })

    // 获取数据库中用户的应用数据
    db.collection('userData').where({
      _openid: _openid,
    }).get({
      success: res => {
        console.log("查询返回值", res)
        var _id = res.data[0]._id;
        this.setData({
          countID: _id,
        })
        // console.log("用户数据3:", this.data.username);
      }
    })
    this.paihang()

  },

  paihang(){
    //按答对数量排序数据
    db.collection('userData').where({
    }).orderBy('max_num', 'desc').get({
      success: res => {
        console.log(res)
        var rank = []
        for (var i = 0; i < res.data.length; i++) {
          //if(res.data[i].max_num==0)break;
          if (res.data[i].max_num != 0) {
            rank.push({ 'username': res.data[i].username, 'max_num': res.data[i].max_num, 'img': res.data[i].img })
          }
          
        }
        this.setData({
          rank: rank
        })
        // console.log("用户数据3:", this.data.username);
      }
    })
  },

  onReachBottom: function () {//下拉加载
  },

  // 点击下拉显示框
  selectTap() {
    this.setData({
      show: !this.data.show
    });
  },
  page_selectTap(){
    this.setData({
      show:false
    });
  },
  // 点击下拉列表
  optionTap(e) {
    let Index = e.currentTarget.dataset.index;//获取点击的下拉列表的下标
    switch (Index) {
      case 0: this.setData({ list: list0,listnum:2894}); break;
      case 1: this.setData({ list: list1, listnum:2084}); break;
      case 2: this.setData({ list: list2, listnum:1526 }); break;
      case 3: this.setData({ list: list3, listnum:3656}); break;
      case 4: this.setData({ list: list4, listnum:3837}); break;
      case 5: this.setData({ list: list5, listnum:817}); break;
    }
    this.setData({
      index: Index,
      show: !this.data.show
    });
    console.log(this.data.selectData[Index])
  },

})

